import * as React from 'react'
import { View, ScrollView, Text, StandardProps, Image } from '@tarojs/components'
import './index.scss'
type Prop = {
    /**滚动方向，默认垂直滚动 */
    scrollY?: boolean,
    /**控制刷新状态，默认没有 */
    refreshState?: RefreshState,
    /**上啦刷新 */
    onHeaderRefresh?: Function,
    /**下拉加载 */
    onFooterRefresh?: (info: any) => void,
    onEmptyRefresh?: () => React.ReactNode,

    reload?: Function,
    children?: React.ReactNode,
    /**内容器样式 */
    containerStyle?: React.CSSProperties
}
export enum RefreshState {
    Idle = 'Idle',
    HeaderRefreshing = 'HeaderRefreshing',
    FooterRefreshing = 'FooterRefreshing',
    NoMoreData = 'NoMoreData',
    Failure = 'Failure',
    EmptyData = 'EmptyData',
    None = 'None',
}

const RefreshText = {
    HeaderRefreshing: '上拉刷新，正在加载..',
    FooterRefreshing: '下拉加载，正在加载..',
    Failure: '服务器正在出小差，点击重新加载～',
    NoMoreData: '已经全部加载完毕',
    EmptyData: '暂无数据～',
    Idle: `LOADING～`,
}



export default (props: Prop & StandardProps) => {
    const {
        scrollY = true,
        refreshState = RefreshState.None,
        onHeaderRefresh,
        onFooterRefresh,
        onEmptyRefresh,
        reload,
        children,
        containerStyle,
        ...rest
    } = props


    let ListHeaderComponent = React.useMemo(() => {
        switch (refreshState) {
            case RefreshState.HeaderRefreshing:
                return (
                    <View style={styles.header}>
                        <Image src={require('./loading1.png')} className='loading' mode='aspectFit' />
                        <Text style={styles.refreshText}>{RefreshText.HeaderRefreshing}</Text>
                    </View>
                )
            default:
                return <View />
        }
    }, [refreshState])

    let ListFooterComponent = React.useMemo(() => {
        switch (refreshState) {
            case RefreshState.Idle: {
                return (
                    <View style={styles.footer}>
                        <Image src={require('./loading1.png')} className='loading' mode='aspectFit' />
                        <Text style={styles.refreshText}>{RefreshText.Idle}</Text>
                    </View>
                )
            }
            case RefreshState.FooterRefreshing:
                return (
                    <View style={styles.footer}>
                        <Image src={require('./loading1.png')} className='loading' mode='aspectFit' />
                        <Text style={styles.refreshText}>{RefreshText.FooterRefreshing}</Text>
                    </View>
                )
            case RefreshState.NoMoreData:
                return (
                    <View style={styles.footer}>
                        <Text style={styles.refreshText}>{RefreshText.NoMoreData}</Text>
                    </View>
                )
            case RefreshState.Failure:
                return (
                    <View style={styles.footer} onClick={() => reload && reload()}>
                        <Text style={styles.refreshText}>{RefreshText.Failure}</Text>
                    </View>
                )
            case RefreshState.EmptyData:
                if (onEmptyRefresh)
                    return onEmptyRefresh()
                return (
                    <View style={styles.footer} onClick={() => reload && reload()}>
                        <Text style={styles.refreshText}>{RefreshText.EmptyData}</Text>
                    </View>
                )
            default:
                return <View />
        }
    }, [refreshState])

    const [state, dispatch] = React.useReducer((state, action) => ({ ...state, ...action }), {
        refresherTriggered: false,
    })

    const ref = React.useRef()

    const ScrollTopRef = React.useRef<number>(0)

    React.useEffect(() => {

    }, [])

    return (
        <View
            style={{
                display: 'flex', flex: 1,
                overflow: 'hidden',
                backgroundColor: 'transparent',
                ...rest.style as React.CSSProperties
            }}>

            <ScrollView
                ref={ref}
                style={{ flex: 1 }}
                refresherTriggered={state.refresherTriggered}
                scrollY={scrollY}
                scrollX={!scrollY}
                enableFlex
                enhanced
                bounces
                onScroll={async e => {
                    let ScrollTop = e.detail.scrollTop
                    let scrollHeight = e.detail.scrollHeight
                    let clientHeight = (ref.current as any)?.clientHeight
                    // //console.log({ ScrollTop, scrollHeight ,clientHeight},)

                    let offset = Math.min(20, scrollHeight * 0.5)

                    if (offset > 0) {
                        /**触发上拉刷新 */
                        if (ScrollTop < offset) {
                            if (ScrollTop <= ScrollTopRef.current) {
                                if (refreshState == RefreshState.HeaderRefreshing) return
                                if (refreshState == RefreshState.FooterRefreshing) return
                                dispatch({
                                    refresherTriggered: true,
                                })
                                onHeaderRefresh && onHeaderRefresh(RefreshState.HeaderRefreshing)
                            }
                        }
                        /**触发下拉加载 */
                        else if ((scrollHeight - ScrollTop - clientHeight) < offset) {
                            if (screenTop > ScrollTopRef.current) {
                                if (refreshState == RefreshState.Idle) {
                                    onFooterRefresh && onFooterRefresh(refreshState);
                                }
                            }

                        }

                    }
                    ScrollTopRef.current = ScrollTop

                }}

            >
                {ListHeaderComponent}
                <View style={{ display: 'flex', flexDirection: 'column', ...containerStyle }}>{children}</View>
                {ListFooterComponent}
            </ScrollView>

        </View>
    )

}



const styles: Record<string, React.CSSProperties> = {
    header: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        height: '35px',
    },
    footer: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        height: '44px',
    },
    refreshText: {
        fontSize: '14px',
        color: '#DAD7DA',
    }
}




// const Wait = (timeout = 350) => {
//     return new Promise(resolve => {
//         setTimeout(resolve, timeout);
//     });
// }
